package com.anuyun.ms.base.util;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日期处理工具 主要使用LocalDateTime 和 LocalDate 依赖JDK8
 * 
 * @author yyf
 * @date 2019年8月29日
 */
public class DateUtil {

	/**
	 * 获取当天时间字符串
	 * 
	 * @param format 字符串格式 例：yyyyMMdd HHmmss
	 * @return
	 */
	public static String getNowTime(String format) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		LocalDateTime dateTime = LocalDateTime.now();
		String dateString = dateTime.format(formatter);
		return dateString;
	}

	/**
	 * 获取昨天的日期字符串
	 * 
	 * @param format 字符串格式 例：yyyyMMdd HHmmss
	 * @return
	 */
	public static String getYesterday(String format) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		LocalDateTime dateTime = LocalDateTime.now().minusDays(1);
		String dateString = dateTime.format(formatter);
		return dateString;
	}

	/**
	 * 获取七天前的日期字符串
	 * 
	 * @param format 字符串格式 例：yyyyMMdd HHmmss
	 * @return
	 */
	public static String getPreWeekDay(String format) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		LocalDateTime dateTime = LocalDateTime.now().minusDays(7);
		String dateString = dateTime.format(formatter);
		return dateString;
	}

	/**
	 * 字符串转LocalDateTime
	 * 
	 * @param timeString
	 * @param format
	 * @return
	 */
	public static LocalDateTime toLocalDateTime(String timeString, String format) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		return LocalDateTime.parse(timeString, formatter);
	}

	/**
	 * LocalDateTime 转字符串
	 * 
	 * @param dateTime
	 * @param format
	 * @return
	 */
	public static String toString(LocalDateTime dateTime, String format) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		return dateTime.format(formatter);
	}

	/**
	 * dateTime是否已经过去seconds
	 * @param dateTime	时间字符串
	 * @param seconds	过期时间(s)
	 * @return
	 */
	public static boolean isTimeOut(LocalDateTime dateTime, long seconds) {
		LocalDateTime now = LocalDateTime.now();
		return dateTime.plusSeconds(seconds).isBefore(now);
	}
	
	/**
	 * 两个时间相差毫秒数
	 * @param dateTime
	 * @return
	 */
	public static long differMilliSeconds(LocalDateTime dateTime,LocalDateTime dateTimeNext) {
		Duration duration = Duration.between(dateTime,dateTimeNext);
		return duration.toMillis();
	}
	
	
	/**
	 * 与当前时间相差秒数
	 * @param dateTime
	 * @return
	 */
	public static long differSeconds(LocalDateTime dateTime) {
		LocalDateTime now = LocalDateTime.now();
		Duration duration = Duration.between(now,dateTime);
		return duration.getSeconds();
	}
	

	
	
	/**
	 * 与当前时间相差分钟数
	 * @param dateTime
	 * @return
	 */
	public static long differMinutes(LocalDateTime dateTime) {
		LocalDateTime now = LocalDateTime.now();
		Duration duration = Duration.between(dateTime,now);
		return duration.toMinutes();
	}

}
